<!--
 * @Author: anxia.ack anchenkai@come-future.com
 * @Date: 2025-04-16 11:47:58
 * @LastEditors: anxia.ack anchenkai@come-future.com
 * @LastEditTime: 2025-04-19 19:42:25
 * @FilePath: /free-learning/src/views/course-manage/course-audit/index.vue
-->
<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox, FormRules } from "element-plus";
import {
  getCourseAudiPageList,
  auditCourse,
  getCourseAuditInfo,
  getCourseAuditHistory,
} from "@/api/course/course-audit";
import type { CourseAudit, CourseAuditPageVO, CourseInfoVO } from "@/api/course/course-audit/type";
import { CourseStatus } from "@/api/course/course-mange/type";
import { getList } from "@/api/system/course-category";
import UserAPI from "@/api/system/user";
import { CourseCategoryListVO } from "@/api/system/course-category/type";
import { useUserStore } from "@/store";
import { CourseChapters } from "@/api/course/course-chapters/type";

defineOptions({
  name: "CourseAudit",
});

// 表格数据
const tableData = ref<CourseAuditPageVO[]>([]);
const loading = ref(false);
const total = ref(0);

// 分页参数
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
});

// 搜索条件
const searchForm = reactive({
  keywords: "",
  categoryId: undefined as number | undefined,
  consultantId: undefined as number | undefined,
  status: undefined as number | undefined,
  startBeginTime: "",
  startAfterTime: "",
});

// 选项数据
const categoryOptions = ref<CourseCategoryListVO[]>([]);
const consultantOptions = ref<OptionType[]>([]);

// 获取课程分类列表
const fetchCategories = async () => {
  try {
    const res = await getList();
    categoryOptions.value = res;
  } catch (error) {
    ElMessage.error("获取课程分类失败");
  }
};

// 获取咨询师列表
const fetchConsultants = async () => {
  try {
    const res = await UserAPI.getConsultantOptions();
    consultantOptions.value = res;
  } catch (error) {
    ElMessage.error("获取咨询师列表失败");
  }
};
const statusOptions = [
  { label: "全部", value: undefined },
  { label: "待审核", value: CourseStatus.PendingReview },
  { label: "审核通过", value: CourseStatus.Approved },
  { label: "审核未通过", value: CourseStatus.Rejected },
];
// 获取课程审核列表
const fetchData = async () => {
  loading.value = true;
  try {
    // 构建查询参数，过滤掉空值
    const params: Record<string, any> = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
    };

    // 只添加有值的参数
    if (searchForm.keywords) params.keywords = searchForm.keywords;
    if (searchForm.categoryId) params.categoryId = searchForm.categoryId;
    if (searchForm.consultantId) params.consultantId = searchForm.consultantId;
    if (searchForm.status !== undefined) params.status = searchForm.status;
    if (searchForm.startBeginTime) params.startBeginTime = searchForm.startBeginTime;
    if (searchForm.startAfterTime) params.startAfterTime = searchForm.startAfterTime;

    const res = await getCourseAudiPageList(params);
    tableData.value = res.records || [];
    total.value = res.total || 0;
  } catch (error) {
    ElMessage.error("获取课程审核列表失败");
  } finally {
    loading.value = false;
  }
};

// 处理分页变化
const handlePageChange = (page: number) => {
  pagination.pageNum = page;
  fetchData();
};

// 处理每页条数变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.pageNum = 1;
  fetchData();
};

// 重置搜索条件
const resetSearch = () => {
  searchForm.keywords = "";
  searchForm.categoryId = undefined;
  searchForm.consultantId = undefined;
  searchForm.status = undefined;
  searchForm.startBeginTime = "";
  searchForm.startAfterTime = "";
  pagination.pageNum = 1;
  fetchData();
};

// 审核对话框
const auditDialogVisible = ref(false);
const auditForm = ref<Partial<CourseAudit>>({
  courseId: 0,
  status: CourseStatus.Approved,
  opinion: "",
});
const rules = ref<FormRules>({
  status: [{ required: true, message: "请选择审核状态" }],
  opinion: [{ required: true, message: "请输入审核意见" }],
});
// 课程详情对话框
const detailDialogVisible = ref(false);
const courseDetail = ref<CourseInfoVO | null>(null);
const courseHistory = ref<CourseAudit[]>([]);

// 历史记录对话框
const historyDialogVisible = ref(false);
const currentCourse = ref<CourseAuditPageVO | null>(null);

// 打开审核对话框
const handleAudit = (row: CourseAuditPageVO) => {
  auditForm.value = {
    courseId: row.courseId,
    status: CourseStatus.Approved,
    opinion: "",
  };
  auditDialogVisible.value = true;
};

// 打开详情对话框
const handleDetail = async (row: CourseAuditPageVO) => {
  detailDialogVisible.value = true;
  try {
    const res = await getCourseAuditInfo(row.courseId);
    if (res) {
      courseDetail.value = res;
    } else {
      ElMessage.warning("未获取到课程详情");
    }
  } catch (error) {
    ElMessage.error("获取课程详情失败");
  }
};

// 打开历史记录对话框
const handleHistory = async (row: CourseAuditPageVO) => {
  historyDialogVisible.value = true;
  currentCourse.value = row;
  try {
    const res = await getCourseAuditHistory(row.courseId);
    if (res) {
      courseHistory.value = res;
    } else {
      courseHistory.value = [];
      ElMessage.warning("未获取到审核历史");
    }
  } catch (error) {
    ElMessage.error("获取审核历史失败");
  }
};
const userInfo = useUserStore();
const submitLoading = ref(false);
// 提交审核
const handleSubmitAudit = async () => {
  if (!auditForm.value.opinion) {
    ElMessage.warning("请输入审核意见");
    return;
  }
  try {
    submitLoading.value = true;
    auditForm.value.auditorId = userInfo.userInfo.userId;
    auditForm.value.auditorName = userInfo.userInfo.nickname;
    await auditCourse(auditForm.value as CourseAudit);
    ElMessage.success("审核提交成功");
    auditDialogVisible.value = false;
    fetchData();
  } catch (error) {
    ElMessage.error("审核提交失败");
  } finally {
    submitLoading.value = false;
  }
};

// 获取状态标签类型
const getStatusType = (status: number) => {
  switch (status) {
    case CourseStatus.PendingReview:
      return "warning";
    case CourseStatus.Approved:
      return "success";
    case CourseStatus.WaitingPublish:
      return "success";
    case CourseStatus.Rejected:
      return "danger";
    default:
      return "info";
  }
};

// 获取状态文本
const getStatusText = (status: number) => {
  switch (status) {
    case CourseStatus.PendingReview:
      return "待审核";
    case CourseStatus.Approved:
      return "已通过";
    case CourseStatus.WaitingPublish:
      return "已通过";
    case CourseStatus.Rejected:
      return "已拒绝";
    default:
      return "未知";
  }
};

const videoDialogVisible = ref(false);
const videoUrl = ref("");
const handleShowVideo = (row: CourseChapters) => {
  videoDialogVisible.value = true;
  videoUrl.value = row.chapterUrl;
};
onMounted(() => {
  fetchData();
  fetchCategories();
  fetchConsultants();
});
</script>

<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>课程审核管理</span>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keywords" placeholder="请输入课程标题" clearable />
        </el-form-item>
        <el-form-item label="课程分类">
          <el-cascader
            v-model="searchForm.categoryId"
            :options="categoryOptions"
            clearable
            :props="{
              value: 'id',
              label: 'name',
              children: 'children',
              emitPath: false,
              expandTrigger: 'click',
            }"
          />
        </el-form-item>
        <el-form-item label="咨询师">
          <el-select
            v-model="searchForm.consultantId"
            placeholder="请选择咨询师"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="item in consultantOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择审核状态"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value as number"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.startBeginTime"
            type="datetime"
            placeholder="开始时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
          <span class="mx-2">-</span>
          <el-date-picker
            v-model="searchForm.startAfterTime"
            type="datetime"
            placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchData">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table v-loading="loading" :data="tableData" border style="width: 100%">
        <el-table-column type="index" width="50" align="center" />
        <el-table-column prop="title" label="课程标题" min-width="180" show-overflow-tooltip />
        <el-table-column prop="consultantName" label="咨询师" width="120" show-overflow-tooltip />
        <el-table-column prop="categoryName" label="课程分类" width="120" show-overflow-tooltip />
        <el-table-column prop="status" label="审核状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="auditorName" label="审核人" width="120" show-overflow-tooltip />
        <el-table-column prop="auditTime" label="审核时间" width="180" show-overflow-tooltip />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.status === CourseStatus.PendingReview"
              type="success"
              link
              @click="handleAudit(row)"
            >
              审核
            </el-button>
            <el-button type="primary" link @click="handleDetail(row)">查看详情</el-button>
            <el-button type="info" link @click="handleHistory(row)">审核历史</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 审核对话框 -->
    <el-dialog v-model="auditDialogVisible" title="课程审核" width="500px">
      <el-form :rules="rules" :model="auditForm" label-width="100px">
        <el-form-item label="审核结果">
          <el-radio-group v-model="auditForm.status">
            <el-radio :label="CourseStatus.WaitingPublish">通过</el-radio>
            <el-radio :label="CourseStatus.Rejected">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见">
          <el-input
            v-model="auditForm.opinion"
            type="textarea"
            :rows="4"
            placeholder="请输入审核意见"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button v-loading="submitLoading" type="primary" @click="handleSubmitAudit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 历史记录对话框 -->
    <el-dialog v-model="historyDialogVisible" title="审核历史" width="800px">
      <div v-if="currentCourse" class="history-detail">
        <div class="mt-4">
          <el-timeline>
            <el-timeline-item
              v-for="item in courseHistory"
              :key="item.id"
              :type="getStatusType(item.status)"
              :timestamp="item.auditTime"
            >
              <h4>{{ getStatusText(item.status) }}</h4>
              <p>审核人：{{ item.auditorName }}</p>
              <p>审核意见：{{ item.opinion }}</p>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-dialog>

    <!-- 课程信息对话框 -->
    <el-dialog v-model="detailDialogVisible" title="课程信息" width="800px">
      <div v-if="courseDetail" class="course-detail">
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="课程标题">{{ courseDetail.title }}</el-descriptions-item>
          <el-descriptions-item label="课程分类">
            {{ courseDetail.categoryName }}
          </el-descriptions-item>
          <el-descriptions-item label="咨询师">
            {{ courseDetail.consultantName }}
          </el-descriptions-item>
          <el-descriptions-item label="课程状态">
            <el-tag :type="getStatusType(courseDetail.status)">
              {{ getStatusText(courseDetail.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="课程描述" :span="2">
            {{ courseDetail.description }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="mt-4">
          <h3>课程章节</h3>
          <el-table :data="courseDetail.chapters" border style="width: 100%">
            <el-table-column type="index" width="50" align="center" />
            <el-table-column
              prop="chapterName"
              label="章节标题"
              min-width="180"
              show-overflow-tooltip
            />
            <el-table-column prop="chapterOrder" label="章节序号" width="100" align="center" />
            <el-table-column
              prop="chapterDes"
              label="章节描述"
              min-width="200"
              show-overflow-tooltip
            />
            <el-table-column>
              <template #default="{ row }">
                <el-button type="primary" link @click="handleShowVideo(row)">查看视频</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
    <el-dialog v-model="videoDialogVisible" title="视频" width="800px">
      <video :src="videoUrl" controls class="w-full h-full" />
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-form {
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .course-detail {
    h3 {
      margin: 16px 0;
      font-weight: 500;
    }
  }

  .mx-2 {
    margin: 0 8px;
  }

  .history-detail {
    h3 {
      margin: 16px 0;
      font-weight: 500;
    }
  }
}
</style>
